package nullby.yoga.utils;

import java.io.IOException;

import nullby.yoga.R;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class EuropeanYoga extends Service {
	private MediaPlayer player;
	private static String file;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		file = PrefManager.get().getSong(null);
		// Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
		// player = MediaPlayer.create(MyService.this, R.raw.song);
		// player.start();

	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if ("stop".equals(intent.getStringExtra("command"))) {
			if (player != null) {
				player.stop();
				player.reset();
			}
		}
		if ("start".equals(intent.getStringExtra("command"))) {
			if (intent.getStringExtra("file") != null) {

				if (player == null) {
					player = MediaPlayer.create(EuropeanYoga.this, R.raw.check);
					player.setLooping(true);
				}
				if (player != null) {
					if (!file.equals(intent.getStringExtra("file"))) {
						player.stop();
						player.reset();
					}

					try {
						file = intent.getStringExtra("file");
						player.setDataSource(file);
					} catch (IllegalArgumentException e) {
					} catch (IllegalStateException e) {
					} catch (IOException e) {
					}
					try {
						player.prepare();
					} catch (IllegalStateException e) {
					} catch (IOException e) {
					}
					player.start();
					player.setLooping(true);
				}
			}
		}
		// Toast.makeText(
		// this,
		// intent.getStringExtra("command") + " ..::.. "
		// + intent.getStringExtra("file"), Toast.LENGTH_SHORT)
		// .show();
		Log.i("LocalService", "Received start id " + startId + ": " + intent);
		// We want this service to continue running until it is explicitly
		// stopped, so return sticky.
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (player != null) {
			player.stop();
			player.reset();
			player.release();
			player = null;
		}
		// Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
	}

}
